<script setup>
import { ref, reactive, computed, toRefs, onBeforeMount } from 'vue'
import ClusterNamespaceSelector from './ClusterNamespaceSelector.vue'
import { createDeploymentHandler } from '../../api/deployment'
import { getSecretListHandler } from '../../api/secret.js'
import { getServiceListHandler } from '../../api/service.js'
import { Check, Close } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import Table from './Table.vue'
import ScheduleConfig from './scheduling/ScheduleConfig.vue'
import Container from './scheduling/Container.vue'
import Volume from './scheduling/Volume.vue'
import { list2Object, object2List } from '../../utils/utils'

import { useItem } from '../../store/index.js' //从pinia导入数据
import { storeToRefs } from 'pinia'


const activeName = ref('basic')
const labelActiveName = ref('controllerAnnos')

const props = defineProps({
    resourceType: {
        type: String,
        default: 'Deployment'
    },
    method: {
        type: String,
        default: 'Create'
    }
})
// 定义资源操作事件
const emits = defineEmits(['submit'])
const useItemer = useItem()
const data = reactive({
    clusterId: "",
    namespace: "",
    item: {
        metadata: {
            name: "",
            labels: {},
            annotations: {}
        },
        spec: {
            selector: {
                matchLabels: {}
            },
            replicas: 1,
            template: {
                metadata: {
                    labels: {},
                    annotations: {}
                },
                spec: {
                    imagePullSecrets: [],
                    dnsPolicy: 'ClusterFirst',
                    hostNetwork: false,
                }
            }
        }
    },
    autoCreateService: true,
    registrySecretList: [],
    dnsPolicyOptions: [
        {
            value: 'ClusterFirst',
            label: 'ClusterFirst'
        },
        {
            value: 'Default',
            label: 'Default'
        },
        {
            value: 'ClusterFirstWithHostNet',
            label: 'ClusterFirstWithHostNet'
        },
        {
            value: 'None',
            label: 'None'
        }
    ],
    options: {
        controllerAnnoList: [],
        controllerLabelList: [],
        podAnnoList: [],
        podLabelList: [],
        nodeSelectorList: [],
        serviceList: [],
        rules: {
            'name': [
                { required: true, message: '请输入资源名称', trigger: 'blur'}
            ],
            'serviceName': [
                { required: true, message: '请选择serviceName', trigger: 'blur'}
            ]
        }
    }

})
const itemRef = ref()
let autoCreateLabel = ref("true")

// 获取registry类型的secret方法
const getRegistrySecretList = () => {
    const getSecretListParas = {
        clusterId: data.clusterId,
        namespace: data.namespace,
        labelSelector: '',
        fieldSelector: 'type=kubernetes.io/dockerconfigjson'
    }
    getSecretListHandler(getSecretListParas).then(
        (res) => {
            res.data.data.items.forEach((item) => {
                if (data.registrySecretList == null || data.registrySecretList == undefined) {
                    data.registrySecretList = []
                }
                data.registrySecretList.push({
                    name: item.metadata.name
                })
            })
            console.log("secretList:",data.registrySecretList)
        }
    )
}
const namespaceRollback = (clusterId, namespace) => {
    console.log("namespace changed: ", clusterId, namespace)
    data.clusterId = clusterId
    data.namespace = namespace
    useItemer.clusterId = clusterId
    useItemer.namespace = namespace
    useItemer.item.metadata.namespace = namespace
    getRegistrySecretList()
}
const selectChanged = ()=> {
    console.log("item:", useItemer.item)
}


// 提示hostNetwork
const hostNetworkChanged = (val) => {
    if(val) {
        ElMessage({
            message: '开启hostNetwork会直接占用宿主机网络和端口',
            type: 'warning'
        })
    }
    return
}

const submitHandler = (tag) => {
    itemRef.value.validate((valid) => {
        if (valid) {// 校验成功回调函数创建资源
            emits('submit', tag, data.autoCreateService)
        }else {
            ElMessage({
                message: "请完善表单内容",
                type: "warning"
            })
        }
    })
}

const submit = (tag) => {
    if (data.autoCreateService && tag != 'yaml') { // 自动添加service 判断至少存在一个端口
        let portCounter = 0
        useItemer.item.spec.template.spec.containers.forEach((c) => {
            portCounter += c.ports.length
        });
        if (portCounter == 0) {
            ElMessage.error("自动添加service需要至少一个容器端口，请检查")
            return
        }
    }
    let controllerAnnosObj = {}
    let controllerLabelsObj = {}
    let podAnnosObj = {}
    let podLabelsObj = {}
    if (autoCreateLabel.value == "true") { // 数据二次处理 1.list转object
        // 自动生成label
        const obj = {
            app: useItemer.item.metadata.name
        }
        controllerAnnosObj = obj
        controllerLabelsObj = obj
        podAnnosObj = obj
        podLabelsObj = obj
    } else {
        controllerAnnosObj = list2Object(data.options.controllerAnnoList)
        controllerLabelsObj = list2Object(data.options.controllerLabelList)
        podAnnosObj = list2Object(data.options.podAnnoList)
        podLabelsObj = list2Object(data.options.podLabelList)
    }
    useItemer.item.metadata.labels = controllerLabelsObj
    useItemer.item.metadata.annotations = controllerAnnosObj
    if (props.resourceType != 'CronJob'){
        useItemer.item.spec.template.metadata.labels = podLabelsObj
        useItemer.item.spec.template.metadata.annotations = podAnnosObj
        useItemer.item.spec.selector.matchLabels = podLabelsObj
    }

    useItemer.item.spec.template.spec.nodeSelector = list2Object(data.options.nodeSelectorList)
    console.log("item:",useItemer.item)
    if(data.autoCreateService && props.resourceType == 'StatefulSet') {
        // 自动生成headless Service
        useItemer.item.spec.serviceName = useItemer.item.metadata.name
    }
    submitHandler(tag)
}

// 当绑定service的类型产生变化时调用查询service调用接口
const radioChanged = () => {
    if(!data.autoCreateService){useItemer.item.spec.serviceName = ''}
}
const visibleChanged = (visible) => {
    if(!visible){return}
    const getListParas = {
        clusterId: data.clusterId,
        namespace: data.namespace,
        labelSelector: '',
        fieldSelector: ''
    }
    getServiceListHandler(getListParas).then(
        (res) => {
            data.options.serviceList = []
            res.data.data.items.forEach((item) => {
                if(item.spec.clusterIP == 'None'){
                    data.options.serviceList.push(item)
                }
            })
            console.log("serviceList:",res)
        }
    )
}
onBeforeMount(() => {
    if (props.method != 'Create') {
        autoCreateService.value = false
        autoCreateLabel.value = 'false'
        //把当前存在的label转成list
        data.options.controllerAnnoList = object2List(useItemer.item.metadata.annotations)
        data.options.controllerLabelList = object2List(useItemer.item.metadata.labels)
        if (props.resourceType != 'CronJob'){
            data.options.podAnnotationsList = object2List(useItemer.item.spec.template.metadata.annotations)
            data.options.podLabelList = object2List(useItemer.item.spec.template.metadata.labels)
        }
        data.options.nodeSelectorList = object2List(useItemer.item.spec.template.spec.nodeSelector)
    }
})

const { registrySecretList, dnsPolicyOptions, autoCreateService, options } = toRefs(data)
const { item } = storeToRefs(useItem())
</script>

<template>
    <el-card class="box-card">
        <!-- 创建资源表单 -->
        <el-form
        :model="item"
        ref="itemRef"
        label-width="140"
        >
            <!-- 外层tabs -->
            <el-tabs v-model="activeName" class="demo-tabs">
                <el-tab-pane label="基本配置" name="basic" class="tab-pane">
                    <el-card class="box-card">
                        <template #header>
                        <div class="auto-space-between">
                            <!-- namespace和cluster选择器 -->
                            <div>
                                <ClusterNamespaceSelector
                                :cluster-readonly="props.method =='Update'"
                                :namespace-readonly="props.method == 'Update'"
                                @namespaceChangedRollback="namespaceRollback">
                                </ClusterNamespaceSelector>
                            </div>
                        </div>
                        </template>
                        <div>
                            <!-- 基本配置 名称、副本数、密钥、DNS-->
                            <el-row :gutter="20">
                                <el-col :span="6">
                                    <el-form-item label="名称" prop="metadata.name" :rules="options.rules.name" required>
                                        <el-input :disabled="props.method == 'Update'" v-model.trim="item.metadata.name" style="width:180px" placeholder="请输入资源名称"/>
                                    </el-form-item>
                                </el-col>

                                <el-col :span="6">
                                    <el-form-item label="副本数" prop="spec.replicas" v-if="props.resourceType == 'Deployment'||props.resourceType == 'StatefulSet'">
                                        <el-input-number v-model="item.spec.replicas" :min="0" :max="100"/>
                                    </el-form-item>
                                </el-col>

                                <el-col :span="6">
                                    <el-form-item label="私有仓库密钥" prop="spec.template.spec.imagePullSecrets">
                                        <el-select v-model="item.spec.template.spec.imagePullSecrets" multiple collapse-tags value-key="name" placeholder="选择仓库密钥" @change="selectChanged">
                                            <el-option
                                            v-for="s in registrySecretList"
                                            :key="s.name"
                                            :label="s.name"
                                            :value="s"
                                            >
                                            </el-option>
                                        </el-select>
                                    </el-form-item>
                                </el-col>

                                <el-col :span="6">
                                    <el-form-item label="DNS策略" prop="spec.template.spec.dnsPolicy">
                                        <el-select v-model="item.spec.template.spec.dnsPolicy">
                                            <el-option
                                            v-for="s in dnsPolicyOptions"
                                            :key="s.value"
                                            :label="s.label"
                                            :value="s.value"
                                            >
                                            </el-option>
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <!-- 基本配置 更新方式 hostNetwork -->
                            <el-row :gutter="20">
                            
                                <slot name="strategy"></slot>

                                <el-col :span="6" v-if="props.resourceType != 'CronJob'">
                                    <el-form-item label="使用宿主机网络" prop="spec.template.spec.hostNetwork">
                                        <el-switch
                                            v-model="item.spec.template.spec.hostNetwork"
                                            class="mt-2"
                                            inline-prompt
                                            :active-icon="Check"
                                            :inactive-icon="Close"
                                            @change="hostNetworkChanged"
                                        />
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <!-- 基本配置 标签配置 自动添加service -->
                            <el-row :gutter="20">
                                <el-col :span="6" v-if="props.method != 'Update'">
                                    <el-form-item label="标签及注释" prop="">
                                        <el-radio-group v-model="autoCreateLabel">
                                            <el-radio value="true" size="large">自动生成</el-radio>
                                            <el-radio value="false" size="large">手动配置</el-radio>
                                        </el-radio-group>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="6" v-if="props.method != 'Update' && props.resourceType != 'CronJob'">
                                    <el-form-item label="自动添加service" prop="" v-if="props.resourceType == 'Deployment' || props.resourceType =='DaemonSet'">
                                        <el-switch
                                            v-model="autoCreateService"
                                            class="mt-2"
                                        />
                                    </el-form-item>
                                    <el-form-item label="绑定Service" prop="" v-else="props.resourceType == 'StatefulSet'">
                                        <el-radio-group @change="radioChanged()" v-model="autoCreateService">
                                            <el-radio :value="true">自动生成service并绑定</el-radio>
                                            <el-radio :value="false">选择已有service</el-radio>
                                        </el-radio-group>
                                    </el-form-item>
                                </el-col>
                                <el-col  :span="6" v-if="!autoCreateService && props.resourceType == 'StatefulSet'">
                                    <el-form-item label="选择service" required prop="spec.serviceName" :rules="options.rules.serviceName">
                                        <el-select v-model="item.spec.serviceName" style="width:180px"
                                        placeholder="请选择绑定的service"
                                        @visible-change="visibleChanged"
                                        >
                                         <el-option
                                         v-for="service in options.serviceList"
                                         :key="service.metadata.name"
                                         :label="service.metadata.name"
                                         :value="service.metadata.name"
                                         >
                                         </el-option>
                                        </el-select>
                                    </el-form-item>
                                    
                                </el-col>
                                <!-- CronJob -->
                                <slot name="specialConfig"></slot>
                            </el-row>
                        </div>
                    </el-card>
                    <!-- 标签配置 -->
                    <el-card v-if="autoCreateLabel=='false'" style="margin-top: 20px;">
                        <el-tabs v-model="labelActiveName" class="demo-tabs" tab-position="left">
                            <el-tab-pane label="控制器注释" name="controllerAnnos">
                                <Table :list="options.controllerAnnoList"></Table>
                            </el-tab-pane>
                            <el-tab-pane label="控制器标签" name="controllerLabels">
                                <Table :list="options.controllerLabelList"></Table>
                            </el-tab-pane>
                            <el-tab-pane label="Pod注释" name="PodAnnos"  v-if="props.resourceType != 'CronJob'">
                                <Table :list="options.podAnnoList"></Table>
                            </el-tab-pane>
                            <el-tab-pane label="Pod标签" name="PodLabels" v-if="props.resourceType != 'CronJob'">
                                <Table :readonly="props.method=='Update'" :list="options.podLabelList"></Table>
                            </el-tab-pane>
                        </el-tabs>
                    </el-card>
                </el-tab-pane>
                <!-- 节点选择器，亲和力 -->
                <el-tab-pane label="高级配置" name="affinity" class="tab-pane">
                    <ScheduleConfig :list="options.nodeSelectorList"></ScheduleConfig>
                </el-tab-pane>

                <el-tab-pane label="存储卷配置" name="volume" class="tab-pane">
                    <Volume></Volume>
                </el-tab-pane>

                <el-tab-pane label="容器配置" name="container" class="tab-pane">
                    <Container :method="props.method" :resource-type="props.resourceType"></Container>
                </el-tab-pane>

                <el-tab-pane label="初始化容器" name="init-containers" class="tab-pane">
                    <Container container-type="init" :method="props.method" :resource-type="props.resourceType"></Container>
                </el-tab-pane>
            </el-tabs>
            <span style="display: block;margin-top: 30px;" class="span-button">
                <el-button @click="submit('yaml')">yaml</el-button>
                <el-button type="primary" @click="submit()">
                    {{ props.method=="Update"?"更新":"创建" }}
                </el-button>
            </span>
        </el-form>
    </el-card>
</template>

<style scoped>
.tab-pane {
    height: 750px;
}
</style>
